package com.tanhua.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.service.ManagerService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.FreezeDto;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author wjs
 * @version 1.0
 * @date 2022/1/3 0003 下午 3:00
 */

@Service
public class ManagerServiceImpl implements ManagerService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageResult findAllUsers(Integer page, Integer pagesize) {

        IPage<UserInfo> iPage = userInfoApi.findAllPage(page, pagesize);

        List<UserInfo> infos = iPage.getRecords();
        List<UserInfo> list = infos.stream().map(userInfo -> {
            if (redisTemplate.hasKey(Constants.FREEZE_USER + userInfo.getId())) {
                userInfo.setUserStatus("2");
            }
            return userInfo;
        }).collect(Collectors.toList());

        return new PageResult(page, pagesize, iPage.getTotal(), list);

    }

    @Override
    public UserInfo findUserById(Long userId) {
        UserInfo info = userInfoApi.findById(userId);
        if (redisTemplate.hasKey(Constants.FREEZE_USER+info.getId())) {
            info.setUserStatus("2");
        }
        /*if (redisTemplate.hasKey(Constants.FREEZE_USER + info.getId() + 1)
                || redisTemplate.hasKey(Constants.FREEZE_USER + info.getId() + 2)
                || redisTemplate.hasKey(Constants.FREEZE_USER + info.getId() + 3)) {
            info.setUserStatus("2");
        }*/
        return info;
    }

    @Override
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {

        PageResult pageResult = videoApi.findAllPageByUserId(page, pagesize, uid);

        List<Video> list = (List<Video>) pageResult.getItems();
        if (list.isEmpty()) {
            return new PageResult();
        }
        List<Long> ids = list.stream().map(Video::getUserId).collect(Collectors.toList());

        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
        List<VideoVo> vos = list.stream().filter(video -> map.get(video.getUserId()) != null)
                .map(video -> VideoVo.init(map.get(video.getUserId()), video))
                .collect(Collectors.toList());
        pageResult.setItems(vos);

        return pageResult;
        //return videoApi.findAllPageByUserId(page, pagesize, uid);
    }

    @Override
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {

        PageResult pageResult = movementApi.findPageByUserIdAndState(page, pagesize, uid, state);

        List<Movement> list = (List<Movement>) pageResult.getItems();
        if (list.isEmpty()) {
            return new PageResult();
        }
        List<Long> userIds = list.stream().map(Movement::getUserId).collect(Collectors.toList());

        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<MovementsVo> vos = list.stream().filter(movement -> map.get(movement.getUserId()) != null)
                .map(movement -> MovementsVo.init(map.get(movement.getUserId()), movement))
                .collect(Collectors.toList());
        pageResult.setItems(vos);

        return pageResult;
    }

    @Override
    public ResponseEntity findMovementById(String id) {

        Movement movement = movementApi.findById(id);
        UserInfo info = userInfoApi.findById(movement.getUserId());

        return ResponseEntity.ok(MovementsVo.init(info, movement));
    }

    @Override
    public ResponseEntity findCommentsByMessageId(Integer page, Integer pagesize, String messageID) {
        Movement movement = movementApi.findById(messageID);

        List<Comment> list = commentApi.findPageComments(String.valueOf(movement.getId()), CommentType.COMMENT, page, pagesize);
        Long count = commentApi.countByMoventId(String.valueOf(movement.getId()), CommentType.COMMENT);
        if (list == null || list.isEmpty()) {
            return ResponseEntity.ok(new PageResult(page, pagesize, count, null));
        }

        //获取评论用户id
        List<Long> userIds = list.stream().map(comment -> comment.getUserId()).collect(Collectors.toList());

        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        List<CommentVo> vos = list.stream()
                .filter(comment -> map.get(comment.getUserId()) != null)
                .map(comment -> CommentVo.init(map.get(comment.getUserId()), comment))
                .collect(Collectors.toList());

        PageResult pageResult = new PageResult(page, pagesize, count, vos);

        return ResponseEntity.ok(pageResult);
    }

    @Override
    public Map userFreeze(FreezeDto dto) {

        //构造key
        String key = Constants.FREEZE_USER + dto.getUserId();
//        String key = Constants.FREEZE_USER + dto.getUserId() + dto.getFreezingRange();

        //构造失效时间
        int days = 0;
        if (dto.getFreezingTime().equals(1)) {
            days = 3;
        }
        if (dto.getFreezingTime().equals(2)) {
            days = 7;
        }

        String value = JSON.toJSONString(dto);

        if(days!=0){
            redisTemplate.opsForValue().set(key, value, Duration.ofDays(days));
        }else {
            redisTemplate.opsForValue().set(key, value);
        }

        Map map = new HashMap();
        map.put("message", "冻结成功");

        return map;
    }

    @Override
    public Map userUnfreeze(FreezeDto dto) {
        redisTemplate.delete(Constants.FREEZE_USER + dto.getUserId());
//        redisTemplate.delete(Constants.FREEZE_USER+dto.getUserId()+dto.getFreezingRange());
        Map map = new HashMap();
        map.put("message", "解冻成功");
        return map;
    }
}
